import React, { Component } from 'react';
import { connect } from 'react-redux';
import { 
  List, 
  SearchBar, 
  PullToRefresh, 
  Empty,
  Button,
  Toast,
  Space,
  Tag
} from 'antd-mobile';
import { 
  SearchOutline, 
  ExclamationCircleOutline,
  FilterOutline,
  CalendarOutline,
  LocationOutline
} from 'antd-mobile-icons';
import { 
  fetchMatches, 
  searchMatches, 
  filterMatches,
  setSearchTerm, 
  setFilter,
  clearSearch,
  clearFilter,
  fieldMap
} from '../../store/reducers/matchSlice';
import styles from './MatchList.module.less';

class MatchList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      refreshing: false,
      showFilter: false,
    };
  }

  componentDidMount() {
    this.loadMatches();
  }

  loadMatches = () => {
    const { dispatch } = this.props;
    dispatch(fetchMatches());
  };

  handleSearch = (value) => {
    const { dispatch, teams } = this.props;
    dispatch(setSearchTerm(value));
    
    if (value.trim()) {
      dispatch(searchMatches({ searchTerm: value, teams }));
    } else {
      dispatch(fetchMatches());
    }
  };

  handleClearSearch = () => {
    const { dispatch } = this.props;
    dispatch(clearSearch());
    dispatch(fetchMatches());
  };

  handleFilter = (filterType, value) => {
    const { dispatch } = this.props;
    dispatch(setFilter({ type: filterType, value }));
    dispatch(filterMatches({ filterType, value }));
    this.setState({ showFilter: false });
  };

  handleClearFilter = () => {
    const { dispatch } = this.props;
    dispatch(clearFilter());
    dispatch(fetchMatches());
  };

  handleRefresh = async () => {
    this.setState({ refreshing: true });
    try {
      await this.loadMatches();
    } finally {
      this.setState({ refreshing: false });
    }
  };

  handleMatchClick = (match) => {
    Toast.show(`点击了比赛: ${this.getTeamName(match.team_id)} vs ${this.getTeamName(match.vs_team_id)}`);
    // 这里可以跳转到比赛详情页或显示详情弹窗
  };

  handleRetry = () => {
    this.loadMatches();
  };

  getTeamName = (teamId) => {
    const { teams } = this.props;
    const team = teams.find(t => t.id === teamId);
    return team ? team.name : `球队${teamId}`;
  };

  getFieldName = (fieldId) => {
    return fieldMap[fieldId] || `场地${fieldId}`;
  };

  formatDateTime = (dateTime) => {
    const date = new Date(dateTime);
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${month}/${day} ${hours}:${minutes}`;
  };

  getScoreStatus = (score) => {
    const [homeScore, awayScore] = score;
    if (homeScore > awayScore) return { status: 'win', text: '胜', color: '#00b578' };
    if (homeScore < awayScore) return { status: 'lose', text: '负', color: '#ff3141' };
    return { status: 'draw', text: '平', color: '#999' };
  };

  truncateComment = (comment, maxLength = 50) => {
    if (comment.length <= maxLength) return comment;
    return comment.substring(0, maxLength) + '...';
  };

  renderMatchItem = (match) => {
    const scoreStatus = this.getScoreStatus(match.score);
    const [homeScore, awayScore] = match.score;
    
    return (
      <List.Item
        key={match.id}
        onClick={() => this.handleMatchClick(match)}
        className={styles.matchItem}
      >
        <div className={styles.matchContent}>
          {/* 比赛时间 */}
          <div className={styles.matchTime}>
            <CalendarOutline className={styles.timeIcon} />
            <span>{this.formatDateTime(match.dateTime)}</span>
          </div>

          {/* 对阵信息 */}
          <div className={styles.matchTeams}>
            <div className={styles.teamInfo}>
              <div className={styles.teamName}>{this.getTeamName(match.team_id)}</div>
              <div className={styles.teamLabel}>主队</div>
            </div>
            
            <div className={styles.vsSection}>
              <div className={styles.scoreDisplay}>
                <span className={styles.score}>{homeScore}</span>
                <span className={styles.separator}>:</span>
                <span className={styles.score}>{awayScore}</span>
              </div>
              <Tag 
                color={scoreStatus.color} 
                className={styles.statusTag}
              >
                {scoreStatus.text}
              </Tag>
            </div>
            
            <div className={styles.teamInfo}>
              <div className={styles.teamName}>{this.getTeamName(match.vs_team_id)}</div>
              <div className={styles.teamLabel}>客队</div>
            </div>
          </div>

          {/* 场地信息 */}
          <div className={styles.matchField}>
            <LocationOutline className={styles.fieldIcon} />
            <span>{this.getFieldName(match.field_id)}</span>
          </div>

          {/* 评论预览 */}
          {match.comment && (
            <div className={styles.matchComment}>
              {this.truncateComment(match.comment)}
            </div>
          )}
        </div>
      </List.Item>
    );
  };

  renderFilterBar = () => {
    const { showFilter } = this.state;
    
    if (!showFilter) return null;

    return (
      <div className={styles.filterBar}>
        <div className={styles.filterTitle}>筛选条件</div>
        <Space wrap>
          <Button 
            size="small" 
            onClick={() => this.handleFilter('result', 'win')}
            className={styles.filterButton}
          >
            主队胜
          </Button>
          <Button 
            size="small" 
            onClick={() => this.handleFilter('result', 'lose')}
            className={styles.filterButton}
          >
            主队负
          </Button>
          <Button 
            size="small" 
            onClick={() => this.handleFilter('result', 'draw')}
            className={styles.filterButton}
          >
            平局
          </Button>
          <Button 
            size="small" 
            onClick={this.handleClearFilter}
            className={styles.clearFilterButton}
          >
            清除筛选
          </Button>
        </Space>
      </div>
    );
  };

  renderEmpty = () => {
    const { searchTerm, filterType } = this.props;
    
    return (
      <Empty
        className={styles.empty}
        image={<SearchOutline style={{ fontSize: 64, color: '#999' }} />}
        description={
          <div className={styles.emptyContent}>
            <div className={styles.emptyText}>
              {searchTerm ? '没有找到相关比赛' : 
               filterType ? '没有符合条件的比赛' : '暂无比赛数据'}
            </div>
            {(searchTerm || filterType) && (
              <Space>
                {searchTerm && (
                  <Button 
                    size="small" 
                    onClick={this.handleClearSearch}
                    className={styles.clearButton}
                  >
                    清空搜索
                  </Button>
                )}
                {filterType && (
                  <Button 
                    size="small" 
                    onClick={this.handleClearFilter}
                    className={styles.clearButton}
                  >
                    清除筛选
                  </Button>
                )}
              </Space>
            )}
          </div>
        }
      />
    );
  };

  renderError = () => {
    return (
      <div className={styles.errorContainer}>
        <Empty
          image={<ExclamationCircleOutline style={{ fontSize: 64, color: '#ff3141' }} />}
          description="加载失败，请重试"
        />
        <Button 
          color="primary" 
          onClick={this.handleRetry}
          className={styles.retryButton}
        >
          重新加载
        </Button>
      </div>
    );
  };

  render() {
    const { 
      filteredMatches, 
      loading, 
      error, 
      searchTerm
    } = this.props;
    const { refreshing, showFilter } = this.state;

    if (error) {
      return (
        <div className={styles.container}>
          {this.renderError()}
        </div>
      );
    }

    return (
      <div className={styles.container}>
        <div className={styles.header}>
          <SearchBar
            placeholder="搜索球队、场地、评论"
            value={searchTerm}
            onChange={this.handleSearch}
            onClear={this.handleClearSearch}
            className={styles.searchBar}
            showCancelButton
          />
          
          <Button 
            size="small" 
            onClick={() => this.setState({ showFilter: !showFilter })}
            className={styles.filterToggle}
          >
            <FilterOutline />
            筛选
          </Button>
        </div>

        {this.renderFilterBar()}

        <div className={styles.content}>
          <PullToRefresh
            onRefresh={this.handleRefresh}
            refreshing={refreshing}
          >
            <List className={styles.matchList}>
              {filteredMatches.length > 0 ? (
                filteredMatches.map(match => this.renderMatchItem(match))
              ) : (
                <List.Item>
                  {this.renderEmpty()}
                </List.Item>
              )}
            </List>
          </PullToRefresh>
        </div>

        {loading && !refreshing && (
          <div className={styles.loading}>
            <div className={styles.loadingText}>加载中...</div>
          </div>
        )}
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  matches: state.matches.matches,
  filteredMatches: state.matches.filteredMatches,
  searchTerm: state.matches.searchTerm,
  filterType: state.matches.filterType,
  filterValue: state.matches.filterValue,
  loading: state.matches.loading,
  error: state.matches.error,
  teams: state.teams.teams,
});

export default connect(mapStateToProps)(MatchList);
